package com.yijumao.shop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yijumao.shop.domain.Orders;
import com.yijumao.shop.domain.User;
import com.yijumao.shop.service.OrderService;
import com.yijumao.shop.utils.AlipayConfig;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author konley
 * @date 2020-11-17 11:21
 */
@Controller()
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    //查看用户订单的方法
    @RequestMapping("/showUserOrders")
    public String showUserOrders(Model model, HttpSession session){
        //根据session取出用户id 并查询用户下的所有订单
        User user = (User) session.getAttribute("user");
        Integer uid = user.getUid();
        List<Orders> orders = orderService.selectByUid(uid);
        //回显订单集合 ： orders --> order --> order_item
        model.addAttribute("orders",orders);

        return "order-list";
    }

    //支付成功回调方法
    @RequestMapping("/rollback")
    public String rollback(String out_trade_no, String trade_no, String total_amount, Model model){
        //更新订单状态为0 表示支付成功
        Orders orders = orderService.selectByPrimaryKey(out_trade_no);
        orders.setState(0);
        orderService.updateByPrimaryKey(orders);

        //存入订单号
        model.addAttribute("out_trade_no", out_trade_no);
        //存入支付宝交易号
        model.addAttribute("trade_no",trade_no);
        //存入交易金额
        model.addAttribute("total_amount",total_amount);
        return "pay-success";
    }

    //支付方法
    @RequestMapping("/order")
    public void order(HttpServletRequest request, HttpServletResponse response,String name, String address, String telephone) throws IOException, AlipayApiException {
        //根据订单号更新地址、姓名和电话号码
        Orders orders = orderService.selectByPrimaryKey(request.getParameter("WIDout_trade_no"));
        orders.setAddress(address);
        orders.setName(name);
        orders.setTelephone(telephone);
        orderService.updateByPrimaryKey(orders);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = "酷玩商城订单";
        //商品描述，可空
        //String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                //+ "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //设置输出类型
        response.setContentType("text/html;charset=utf-8");

        //输出
        response.getWriter().println(result);
    }

}
